package com.taotao.portal.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.taotao.pojo.TbUser;
import com.taotao.portal.service.UserService;

/**
 * 拦截Controller层请求,验证用户信息是否获取,未获取强制跳转登录界面;
 * <p>
 * Title:LoginInterceptor
 * </p>
 * <p>
 * Description:
 * </p>
 * 
 * @author JSJ
 * @date 2017年10月14日下午8:59:23
 */
public class LoginInterceptor implements HandlerInterceptor {
	@Autowired
	private UserService userService;
	@Value("${SSO_LOGIN_URL}")
	private String SSO_LOGIN_URL;

	/**
	 * 调用controller层目标方法前拦截
	 */
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		TbUser user = userService.getUserByToken(request, response);
		// 登录后回调到原请求页面
		StringBuffer redirect = request.getRequestURL();
		if (user == null) {
			response.sendRedirect(SSO_LOGIN_URL + "?redirect=" + redirect);
			return false;
		}
		request.setAttribute("user", user);
		return true;
	}

	/**
	 * 调用完目标方法,渲染视图ModelAndView之前拦截
	 */
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub

	}

	/**
	 * 渲染视图后拦截
	 */
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub

	}

}
